package com.lungolago.bank.dao;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import com.lungolago.bank.commons.dao.GenericJpaDao;
import com.lungolago.bank.domain.UserEntity;

import org.springframework.util.Assert;

/**
 * Data Access Object JAP impl to work with User entity db operations.
 * 
 * @author Franco
 */
public class UserJpaDao extends GenericJpaDao<UserEntity, Long> implements UserDao{

	public UserJpaDao() {
		//TODO research what .class means exactly
		super(UserEntity.class);		
	}

	/**
	 * Checks availability of UserName in db
	 * 
	 * @param UserName
	 * @return true if available
	 */
	public boolean checkAvailability(String userName) {
		//Assert from Spring to check if passed method is not null (static method), 
		//if object is null then it will throw IllegalArgumentException
		Assert.notNull(userName);
		
		//hql query
		//:userName -> is the parameter
		Query query = getEntityManager()
				.createQuery("select count(*) from " + getPersistentClass().getSimpleName()
				+ " u where u.userName = :userName").setParameter("userName", userName);
		
		Long result = (Long) query.getSingleResult();
		
		if (result < 1) {
			return true;
		} else {		
			return false;
		}
		//this if statement could be written as the following logical statement
		//TODO try it out
		//return count < 1;
	}

	/**
	 * Queries user by username
	 * 
	 * @param UserName
	 * @return UserEntity
	 */
	public UserEntity loadUserByUserName(String userName) {
		
		Assert.notNull(userName);
		
		UserEntity user = null;
		
		Query query = getEntityManager().createQuery("select u from " +
				getPersistentClass().getSimpleName() + " u where u.userName = :userName")
				.setParameter("userName", userName);
		
		try {
			user = (UserEntity)query.getSingleResult();
		} catch (NoResultException nre){
			//Do nothing
		}
			
		return user;
		
	}

}
